package com.springboot.wisdom.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

/**
 * 邮件发送工具类
 *
 * @Description
 * @Author LY L
 * @Date 2024-10-18
 */
@Slf4j
@Component
public class EmailUtil {

    /**
     * 发件人邮箱。
     */
    @Value("${spring.mail.username}")
    private String email;
    /**
     * 发件人授权码。
     */
    @Value("${spring.mail.password}")
    private String code;


    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 发送指定HTML内容（String类型）的邮件。（不支持大附件）
     *
     * @param sendToEmail 收件人邮箱。
     * @param emailTitle  邮箱标题。
     * @param htmlText    邮箱正文，支持HTML内容形式的字符串。
     * @return 邮件发送状态。
     */
    public Boolean sendHtmlEmail(String sendToEmail, String emailTitle, String htmlText) {
        try {
            // 创建一个邮件消息
            MimeMessage message = javaMailSender.createMimeMessage();
            // 创建 MimeMessageHelper
            MimeMessageHelper helper = new MimeMessageHelper(message, false);


//            helper.setFrom("3355185791@qq.com", "xcdakhewoepedacj");
//            helper.setTo("1023620624@qq.com");
//            helper.setSubject("张三测试");
//            helper.setText("Hello <strong> World</strong>！", true);

            // 发件人邮箱和名称
            helper.setFrom(email, code);
            // 收件人邮箱
            helper.setTo(sendToEmail);
            // 邮件标题
            helper.setSubject(emailTitle);
            // 邮件正文，第二个参数表示是否是HTML正文
            helper.setText(htmlText, true);

            // 发送
            javaMailSender.send(message);


        } catch (UnsupportedEncodingException | MailException | IllegalArgumentException | MessagingException e) {
//            e.printStackTrace();
            System.out.println("发送邮箱给 【" + sendToEmail + "】 失败！");
            return false;
        }
        System.out.println("发送邮箱给 【" + sendToEmail + "】 成功！");
        return true;
    }


    /**
     * 发送带附件的邮件。
     */
    @Async("mailAsync")
    public Boolean sendAttachmentsMail( String toEmail, String subject, String content, String[] filePaths, String[] fileNames) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(email, code);
            helper.setTo(toEmail);
            helper.setSubject(subject);
            helper.setText(content, true);
            helper.setSentDate(new Date());

            for (int i = 0; i < filePaths.length; i++) {
                // 批量附件。
                FileSystemResource file = new FileSystemResource(new File(filePaths[i]));
                helper.addAttachment(fileNames[i], file);
            }

            javaMailSender.send(message);
            log.info("带附件的邮件已经发送。");
            return true;
        } catch (UnsupportedEncodingException | MessagingException e) {
            log.error("发送带附件的邮件时发生异常！", e);
            return false;
        }
    }


    public Boolean sendDemoEmail() {
        try {
            Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);

            MimeMessage message = new MimeMessage(session);

            message.setFrom(new InternetAddress("1023620624@qq.com"));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress("3355185791@qq.com"));
            message.setSubject("Hello");
            message.setText("This is an anonymous email.");
            props.put("mail.smtp.host", "smtp.qq.com");
            props.put("mail.smtp.port", "25");
            Transport.send(message);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }
}
